<template>
<!--从后端返回信息部分-->
<el-form ref="form" :inline="true">

	<el-form-item label="日期范围">
		<el-date-picker
			v-model="formInline.date_range"
			type="daterange"
			range-separator="-"
			start-placeholder="开始日期"
			end-placeholder="结束日期"
			value-format="YYYY-MM-DD"
		/>
	</el-form-item>

	<el-form-item label="资金流向">
		<el-radio-group v-model="formInline.trend">
			<el-radio-button label="true">欠款</el-radio-button>
			<el-radio-button label="false">支付</el-radio-button>
			<el-radio-button label="全部">全部</el-radio-button>
		</el-radio-group>
	</el-form-item>

	<el-form-item label="处理方">
		<FuzzySearchHandleVer2 @DataUse="handle_auto_complete_in_balance($event as any)"
											 :disable="false"
											 @DataClear="handle1_clear"
		                   />
	</el-form-item>

	<el-form-item>
		<el-button type="primary" @click="handleAdd()">添加出入账记录</el-button>
		<el-button type="primary" @click="return_credit_list()">搜索</el-button>
	</el-form-item>

</el-form>

<!-- 表格部分 -->
<el-table :data="tableData" style="width: 100%">
	<!--选择框-->
	<el-table-column label="记录编号" prop="id" v-if=" false "/>
	<el-table-column label="处理方编号" prop="handle_id" v-if=" false "/>
	<el-table-column label="供应商名称" prop="handle_name"/>
	<el-table-column label="账目日期" prop="pay_date_str"/>
	<el-table-column label="流向">
		<template #default="scope: {row: HandleBalanceList}">
			<span>{{scope.row.trend ? '欠款':'支付'}}</span>
<!--			<el-switch v-model="scope.row.use" size="small" @click="switch_change(scope.row)"/>-->
		</template>
	</el-table-column>
	<el-table-column label="金额" prop="pay_amount"/>
	<el-table-column label="签收人" prop="signatory"/>
	<el-table-column label="操作人" prop="operator"/>
	<el-table-column label="操作日期" prop="operate_date_str"/>

	<el-table-column align="right">
		<template #header>
		</template>

		<template #default="scope">
			<el-button size="small" @click="handleEdit(scope.row)"
			>修改
			</el-button
			>
			<el-button
				size="small"
				type="danger"
				@click="handleDelete(scope.row)"
			>删除
			</el-button
			>
		</template>
	</el-table-column>
</el-table>

<!--添加/修改入账记录-->
<el-dialog v-model="handle_class_dialog_visible"
					 :title=" add_or_update_handle_class "
					 :close-on-click-modal='false'
					 :close-on-press-escape='false'
					 :show-close='false'>
	<el-form :model="crud_handle_balance" :rules="handle_class_rules" ref="handle_class_dialog_ref" :label-position=" 'right' " label-width="120px">

		<el-form-item label="处理方">
			<FuzzySearchHandleVer2 @DataUse="handle_auto_complete_in_balance_dialog($event as any)"
												 :disable="handle_name_not_change"
												 @DataClear="handle2_clear"
												 ref="temp1"/>
		</el-form-item>

		<el-form-item prop="pay_date" label="支付日期">
			<el-date-picker
				v-model="crud_handle_balance.pay_date"
				type="date"
				value-format="YYYY-MM-DD"
			/>
		</el-form-item>

		<el-form-item prop="pay_amount" label="支付金额">
			<el-input v-model="crud_handle_balance.pay_amount" autocomplete="off"/>
		</el-form-item>

		<el-form-item label="资金流向">
			<el-radio-group v-model="crud_handle_balance.trend">
				<el-radio-button :label="true">欠款</el-radio-button>
				<el-radio-button :label="false">支付</el-radio-button>
			</el-radio-group>
		</el-form-item>

		<el-form-item prop="signatory" label="签收人">
			<el-input v-model="crud_handle_balance.signatory" autocomplete="off"/>
		</el-form-item>

	</el-form>
	<template #footer>
      <span class="dialog-footer">
        <el-button @click="close_dialog()">取消</el-button>
        <el-button type="primary" @click="add_or_revise()">保存</el-button>
      </span>
	</template>
</el-dialog>


</template>

<script lang="ts" setup>
import {reactive, Ref, ref} from 'vue'
import {ElMessage, ElMessageBox} from "element-plus";
import type {FormInstance, FormRules} from 'element-plus'
import {useStore} from "@/pinia"
import FuzzySearchHandleVer2, {HandleAutoCompletion} from "@/components/first/FuzzySearchHandleVer2.vue";
import {
	HandleBalanceCRUDResponse,
	HandleBalanceList
} from "@/api/first/HandleManagement/type.ts";
import {reqHandleBalanceCRUD} from "@/api/first/HandleManagement";

const store = useStore()

const close_dialog = () => {
	handle_class_dialog_visible.value = false
	handle_name_not_change.value = false
}

const handle_auto_complete_in_balance_dialog = (cmy: HandleAutoCompletion) => {
	crud_handle_balance.handle_id = cmy.handle_id as number
}
const handle2_clear = () => {
	crud_handle_balance.handle_id = ''
}



//---------------------------------
const handle_auto_complete_in_balance = (cmy: HandleAutoCompletion) => {
	formInline.handle_id = cmy.handle_id as number
}
const handle1_clear = () => {
	formInline.handle_id = ''
}


// 按照条件从后端返回数据 助记码和处理方名称使用模糊搜索
// =============================================
// 向后端返回的检索条件
const formInline = reactive<{
	date_range: [string, string] | null
	handle_id: number | ''
	trend: string
}>({
	date_range: null,
	handle_id: '',
	trend: '全部'
})

// el-form 的ref
const form = ref<FormInstance>()

// 提交信息以便获取表单，提交内容包括根据分页确定起始条数
const return_credit_list = async () => {
	let date_start
	let date_end
	if (formInline.date_range === null) {
		return ElMessage.warning('请选择时间范围')
	} else {
		date_start = formInline.date_range[0]
		date_end = formInline.date_range[1]
	}

	// 若表单验证无误
	const result: HandleBalanceCRUDResponse = await reqHandleBalanceCRUD({
		mode: 'read',
		read: {
			date_start: date_start,
			date_end: date_end,
			handle_id: formInline.handle_id,
			trend: formInline.trend
		}
	})
	tableData.value = result.read as HandleBalanceList[]
	ElMessage.success(result.success?.message)
}

// 通过增加和修改按钮对处理方的增加和修改
let dialogFormModel: string = '' // 决定这个框到底是 修改框还是添加框，只会被赋值为modify和add
const handle_class_dialog_visible: Ref<boolean> = ref(false) // 决定 修改/添加角色框 是否显示
const add_or_update_handle_class: Ref<string> = ref('') // 表单的标题
const handle_class_dialog_ref = ref<FormInstance>() // 增删改的表单的ref
// 弹出框的字段
const crud_handle_balance = reactive<{
	id: number | ''
	handle_id: number | ''
	pay_date: string
	pay_amount: number
	signatory: string
	operator: string
	trend: boolean
}>({
	id: '',
	handle_id: '',
	pay_date: '',
	pay_amount: 0,
	signatory: '',
	operator: '',
	trend: true
})

// 添加/删除框的校验
const handle_class_rules = reactive<FormRules>({
	handle_id: [{
		type: 'string',
		message: '请选择处理方',
		required: true,
	}],
	pay_date: [{
		message: '请选择支付日期',
		required: true,
	}],
	pay_amount: [{
		type: 'string',
		message: '请输入金额',
		required: true,
	}],
	signatory: [{
		type: 'string',
		message: '请输入签收人',
		required: true,
	}],
})



const handle_name_not_change = ref(false)

// 修改处理方信息
const handleEdit = (row: HandleBalanceList) => {
	temp1.value?.input_content(row.handle_name)
	handle_class_dialog_visible.value = true
	add_or_update_handle_class.value = '修改处理方入账信息'
	crud_handle_balance.id = row.id
	crud_handle_balance.pay_date = row.pay_date_str
	crud_handle_balance.pay_amount = row.pay_amount
	crud_handle_balance.signatory = row.signatory
	crud_handle_balance.handle_id = row.handle_id
	crud_handle_balance.trend = row.trend
	dialogFormModel = 'modify'
	handle_name_not_change.value = true
}

const temp1 = ref()
// 添加入账信息

const handleAdd = () => {
	handle_class_dialog_visible.value = true
	handle_class_dialog_ref.value?.clearValidate()
	temp1.value?.clear_input()
	add_or_update_handle_class.value = '添加处理方信息'
	crud_handle_balance.handle_id = ''
	crud_handle_balance.pay_date = ''
	crud_handle_balance.pay_amount = 0
	crud_handle_balance.signatory = store.username
	dialogFormModel = 'add'
}

// 提交添加和修改信息
const add_or_revise = async () => {
	await handle_class_dialog_ref.value?.validate()
	// 添加处理方信息
	if (dialogFormModel === 'add') {
		const result: HandleBalanceCRUDResponse = await reqHandleBalanceCRUD({
			mode: 'create',
			create: {
				handle_id: crud_handle_balance.handle_id as number,
				pay_date: crud_handle_balance.pay_date,
				pay_amount: crud_handle_balance.pay_amount,
				signatory: crud_handle_balance.signatory,
				trend: crud_handle_balance.trend,
				operator: store.username,
			}
		})
		handle_class_dialog_visible.value = false
		ElMessage.success(result.success?.message)
	} else {
    console.log('crud_handle_balance.pay_amount', crud_handle_balance.pay_amount)
		// 修改处理方信息
		const result: HandleBalanceCRUDResponse = await reqHandleBalanceCRUD({
			mode: 'update',
			update: {
				id: crud_handle_balance.id as number,
				pay_date: crud_handle_balance.pay_date,
				pay_amount: crud_handle_balance.pay_amount,
				signatory: crud_handle_balance.signatory,
				trend: crud_handle_balance.trend,
				operator: store.username,
			}
		})
		handle_class_dialog_visible.value = false
		ElMessage.success(result.success?.message)
		handle_name_not_change.value = false
	}
	handle_class_dialog_ref.value?.clearValidate()
}

// 通过每条记录后的删除按钮进行删除
// ===========================
const handleDelete = async (row: HandleBalanceList) => {
	await ElMessageBox.confirm(
		`您确认要删除这条入账记录？`,
		'警告',
		{
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning',
		}
	)
	const result: HandleBalanceCRUDResponse = await reqHandleBalanceCRUD({
		mode: 'delete',
		delete: {
			handle_balance_id: row.id as number,
			operator: store.username,
		}
	})
	await return_credit_list()
	ElMessage.success(result.success?.message)
}

const tableData: Ref<HandleBalanceList[]> = ref([])
</script>